package com.yidianyanglao.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaSecurityJaqCaptchaVerifyResultFetchRequest;
import com.taobao.api.request.AlibabaSecurityJaqLoginpreventionResultFetchRequest;
import com.taobao.api.response.AlibabaSecurityJaqCaptchaVerifyResultFetchResponse;
import com.taobao.api.response.AlibabaSecurityJaqLoginpreventionResultFetchResponse;
import com.yidianyanglao.core.bean.AliSecurityBean;
import com.yidianyanglao.core.enums.Code;
import com.yidianyanglao.core.exception.CustomException;
import org.apache.commons.collections.map.HashedMap;

import java.util.Map;


/**
 * 阿里云安全组件
 * Created by chenkelong on 2016/12/22.
 */
public class AliSecurity {

     final static String url = "http://gw.api.taobao.com/router/rest";
     final static String appkey = "23575101";
     final static String secret = "d9a0b3a7a767c31c9257cc90fb4611d6";

    /**
     * 登录保护结果，检查是否有风险
     * @param aliSecurityBean
     * @return
     * @throws ApiException
     */
    public static Map<String,Object> checkAlisecurity(AliSecurityBean aliSecurityBean){
        Map<String,Object> map = new HashedMap();
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaSecurityJaqLoginpreventionResultFetchRequest req = new AlibabaSecurityJaqLoginpreventionResultFetchRequest();
        Log.info("安全请求参数aliSecurityBean:"+aliSecurityBean.toString());
        if(aliSecurityBean.getPhoneNumber().length() != 11){
            req.setUserId(aliSecurityBean.getPhoneNumber());                   //不是11位时，当前账号是id号码
            req.setIdType(4l);
        }else{
            req.setPhoneNumber(aliSecurityBean.getPhoneNumber());                   //电话号码
        }
        req.setIp(aliSecurityBean.getIp());                                     //ip
        req.setSource(aliSecurityBean.getSource());                             //来源
        req.setProtocolVersion(aliSecurityBean.getProtocolVersion());           //版本
        req.setSdkToken(aliSecurityBean.getSdkToken());                         //获取安全token
        req.setLoginType(aliSecurityBean.getLoginType());                       //登录类型
        AlibabaSecurityJaqLoginpreventionResultFetchResponse rsp = null;
        try{
            rsp = client.execute(req);
        }catch(Exception e){
            throw new CustomException(Code.ERROR,"安全请求异常");
        }
        Log.info("请求参数说明："+aliSecurityBean.toString());
        Log.info("安全请求结果："+rsp);
        JSONObject json = JSON.parseObject(rsp.getBody());
        if(json.get("error_response")!= null){
            map = (Map<String, Object>)json.get("error_response");
            String error_response = (String)map.get("sub_msg");
            throw new CustomException(Code.ERROR,error_response);
        }else{
            //解析json
            map = (Map<String, Object>)json.get("alibaba_security_jaq_loginprevention_result_fetch_response");
            map = (Map<String,Object>)map.get("jaq_account_risk_result");
            map = (Map<String,Object>)map.get("data");
            //解析最终安全结果
            String final_decision = map.get("final_decision").toString();
            map = (Map<String,Object>)map.get("captcha_check_data");
            //解析验证需要的数据
            json = JSON.parseObject(map.get("captcha_client_need_info").toString());
            map.clear();
            map.put("final_decision",final_decision);
            map.put("captcha_client_need_info",json);
        }
        return map;
    }

    /**
     * app端验证验证码
     * @param sessionId
     * @return
     * @throws ApiException
     */
    public static int checkRisk(String sessionId){
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaSecurityJaqCaptchaVerifyResultFetchRequest req = new AlibabaSecurityJaqCaptchaVerifyResultFetchRequest();
        req.setSessionId(sessionId);
        AlibabaSecurityJaqCaptchaVerifyResultFetchResponse rsp = null;
        try{
           rsp = client.execute(req);
        }catch (ApiException e){
            Log.info("接口请求异常{}"+e);
            new CustomException(Code.ERROR, "安全验证你接口异常");

        }
        Log.info("安全验证返回值：{}",rsp.getBody());
        JSONObject json = JSON.parseObject(rsp.getBody());
        int final_decision = 0;
        if(json.get("error_response")!= null){
            Log.info("阿里云安全校验验证码失败，返回内容{}"+json.toString());
            return 1;   //发生异常，暂时放行
        }else{
            Map<String,Object> map = (Map<String, Object>) json.get("alibaba_security_jaq_captcha_verify_result_fetch_response");
            map = (Map<String,Object>)map.get("data");
            final_decision = (Integer)map.get("second_check_result");
        }
        return final_decision;
    }

}
